use crate::components::toats::Toats;

use arboard::Clipboard;
use dioxus::prelude::*;

use tokio::time::{sleep, Duration};
#[derive(Debug, PartialEq, Props, Clone)]
pub struct CopyProps {
    val: String,
}

#[component]
pub fn Copy(props: CopyProps) -> Element {
    let val = props.val.clone();
    let mut cp = use_signal(|| false);
    let mut click_times = use_signal(|| 1);
    let mut debounce_handle = use_signal::<Option<Task>>(|| None);
    rsx! {
            if *cp.read(){

                    Toats {
                        id: rand::random::<u8>().into(),
                        msg: "复制成功！".to_string(),
                        status: crate::components::toats::ToastType::Success,
                    },


            }

        button {
            onclick:move |_|    {
                    let v = val.clone();

                    // 如果有前一个任务，取消它（防抖）
                    if let Some(handle) = debounce_handle.write().take() {
                        handle.cancel(); // 注意：dioxus 的 Task 用 cancel()
                    }

                    let new_handle = spawn(async move {
                        let mut clipboard = Clipboard::new().unwrap();
                        clipboard.set_text(v).unwrap();
                        cp.set(true);

                        sleep(Duration::from_secs(3)).await;
                        if *cp.read() {
                            cp.set(false);
                        }



                    });

                    debounce_handle.set(Some(new_handle));
                            },
            class: "inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [\u{0026}amp;_svg]:pointer-events-none [\u{0026}amp;_svg]:size-4 [\u{0026}amp;_svg]:shrink-0 border hover:bg-accent hover:text-accent-foreground h-9 px-3 border-gray-200 hover:border-blue-300 rounded-lg bg-transparent",
            svg {
                class: "lucide lucide-copy h-4 w-4 mr-1",
                fill: "none",
                height: "24",
                stroke: "currentColor",
                stroke_linecap: "round",
                stroke_linejoin: "round",
                stroke_width: "2",
                view_box: "0 0 24 24",
                width: "24",
                xmlns: "http://www.w3.org/2000/svg",
                rect {
                    height: "14",
                    rx: "2",
                    ry: "2",
                    width: "14",
                    x: "8",
                    y: "8",
                }
                path { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" }
            }
            "复制"
        }
    }
}
